<template>
  <Dialog :title="mode === 'edit' ? '编辑分类' : '新增分类'"
          v-model:model-value="isShowDialog"
          append-to-body
          :width="600"
          @opened="handleOpened"
          @closed="handleClosed">
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
      <el-form-item label="父级分类" v-if="rowData" class="common-form-width">
        <el-input :disabled="true" :model-value="rowData.categoryName" show-word-limit maxlength="20"></el-input>
      </el-form-item>
      <el-form-item label="分类名称" prop="categoryName" class="common-form-width">
        <el-input v-model="form.categoryName" show-word-limit maxlength="20"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import type {FormRules} from "element-plus";
import {ICategoryEditData, ITaskCategoryItem} from "@/api/modules/taskCenter";
import {saveOrUpdateCategory} from "@/api/taskCenter";
import Dialog from "@/components/Dialog.vue"

const props = defineProps<{
  show: boolean,
  mode: 'edit' | 'create',
  rowData: ITaskCategoryItem,
}>()
const emits = defineEmits(['update:show', 'done'])
const isShowDialog = computed({
  set(newValue) {
    emits('update:show', newValue)
  },
  get() {
    return props.show
  }
})

const initForm: () => ICategoryEditData = () => {
  return {
    parentId: undefined,
    categoryName: '',
  }
}
const form = reactive<ICategoryEditData>(initForm())
const formRef = ref()
const formRules = reactive<FormRules>({
  categoryName: [{required: true, trigger: 'blur', message: '请填写分类名称'}],
})

const handleSave = async () => {
  formRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      if (props.rowData.id) {
        form.parentId = props.rowData.id
      }
      const rs = await saveOrUpdateCategory(form)

      if (rs.code === 200) {
        ElMessage.success('创建成功')
        handleDone()
      }
    }
  })
}

const handleDone = () => {
  isShowDialog.value = false
  emits('done')
}

const handleConfirm = () => {
  handleSave()
}

const handleCancel = () => {
  isShowDialog.value = false
}

const handleOpened = () => {
  if (props.mode === 'edit') {
    form.id = props.rowData.id
    form.categoryName = props.rowData.categoryName
  }
}

const handleClosed = () => {
  form.id = undefined
  form.categoryName = ''
}

</script>

<style scoped lang="scss">
@use "@/components/goodsCenter/styles/common.scss";

</style>
